import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutterapptest1/AnimatedDecoratedBox.dart';
import 'package:flutterapptest1/AnimationTestRoute.dart';
import 'package:flutterapptest1/BezierPainterTest.dart';
import 'package:flutterapptest1/ColorsUtils.dart';
import 'package:flutterapptest1/CustomScrollTest.dart';
import 'package:flutterapptest1/CustomScrollViewTestRoute.dart';
import 'package:flutterapptest1/DialogTest.dart';
import 'package:flutterapptest1/DioRoute.dart';
import 'package:flutterapptest1/EventBusTest.dart';
import 'package:flutterapptest1/FileRoute.dart';
import 'package:flutterapptest1/FlexTest.dart';
import 'package:flutterapptest1/FutureBuilderTest.dart';
import 'package:flutterapptest1/HttpClientRoute.dart';
import 'package:flutterapptest1/InheritedWidgetTest.dart';
import 'package:flutterapptest1/InputTest.dart';
import 'package:flutterapptest1/NewScaffTest.dart';
import 'package:flutterapptest1/NotificationRoute.dart';
import 'package:flutterapptest1/news_test_route.dart';
import 'package:flutterapptest1/SelfWidgetTest.dart';
import 'package:flutterapptest1/ScaffTest2.dart';
import 'package:flutterapptest1/SpUtils.dart';
import 'package:flutterapptest1/StaggerAnimation.dart';
import 'package:flutterapptest1/ThemeModityTest.dart';
import 'package:flutterapptest1/ThemeTest.dart';
import 'package:flutterapptest1/TipRoute.dart';
import 'package:english_words/english_words.dart';
import 'package:flutterapptest1/TouchEventTest.dart';
import 'package:fluttertoast/fluttertoast.dart';

void main() {
  runApp(new MaterialApp(
    home: SplashRoute(),
  ));
}

const String NEW_ROUTE = "new_route";
const String TIP_ROUTE = "tip_route";

class SplashRoute extends StatelessWidget {
  final DateTime time = DateTime.now();

  @override
  Widget build(BuildContext context) {
    SpUtils.get("theme").then((onValue) {
      var color = Colors.green;
      if (onValue != null) {
        color = ColorsUtils.colors[onValue];
      }
      int dif = DateTime.now().difference(time).inMilliseconds;
      if (dif < 2000) {
        int sleepTime = 2000 - dif;
        Future.delayed(Duration(milliseconds: sleepTime), () {
          Navigator.pushReplacement(context,
              MaterialPageRoute(builder: (context) {
            return MyApp(color);
          }));
        });
      } else {
        Navigator.pushReplacement(context,
            MaterialPageRoute(builder: (context) {
          return MyApp(color);
        }));
      }
    });
    // TODO: implement build
    return Scaffold(
      body: Center(
        child: ConstrainedBox(
          constraints: BoxConstraints.expand(),
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Image.asset(
                "ic_launcher.png",
                width: 60,
                height: 60,
              ),
              Positioned(
                bottom: 20,
                child: CircularProgressIndicator(),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class MyApp extends StatefulWidget {
  var _themeColors;

  MyApp(this._themeColors);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyAppState(_themeColors);
  }
}

class _MyAppState extends State<MyApp> {
  var eventBus = EventBusTest();
  var _themeColors = Colors.green;

  _MyAppState(this._themeColors);

  // This widget is the root of your application
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    eventBus.on("theme", (arg) {
      setState(() {
        _themeColors = arg;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      initialRoute: "/",
      themeMode: ThemeMode.dark,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: _themeColors,
      ),
      routes: {
        (NEW_ROUTE): (context) => new NewRoute(),
        ("/"): (context) => MyHomePage(title: 'Flutter'),
        (TIP_ROUTE): (context) =>
            TipRoute(text: ModalRoute.of(context).settings.arguments)
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DateTime _lastDateTime;
  var _bottomBarItems = ['基础控件', '布局容器', '事件及动画', '文件及其他'];
  var __index = 0;

  @override
  Widget build(BuildContext context) {
    var theme = Theme.of(context);
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    Widget _widget;
    if (__index == 0) {
      _widget = _getWidget1();
    } else if (__index == 1) {
      _widget = _getWidget2();
    } else if (__index == 2) {
      _widget = _getWidget3(theme: theme);
    } else if (__index == 3) {
      _widget = _getWidget4();
    }
    return WillPopScope(
        child: new Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
            centerTitle: true,
          ),
          body: _widget,
          bottomNavigationBar: BottomNavigationBar(
            type: BottomNavigationBarType.fixed,
            items: _bottomBarItems.map((f) => _bottomGetItem(f)).toList(),
            currentIndex: __index,
            onTap: (index) {
              setState(() {
                __index = index;
              });
            },
          ),
        ),
        onWillPop: () async {
          //创建时间对象，并指定时间
          if (_lastDateTime != null) {
            int diff =
                new DateTime.now().difference(_lastDateTime).inMilliseconds;
            if (diff >= 2000) {
              Fluttertoast.showToast(
                msg: "再按一次退出程序",
                toastLength: Toast.LENGTH_SHORT,
              );
              _lastDateTime = null;
              return false;
            } else {
              exit(0);
              return true;
            }
          } else {
            Fluttertoast.showToast(
              msg: "再按一次退出程序",
              toastLength: Toast.LENGTH_SHORT,
            );
            _lastDateTime = new DateTime.now();
          }
          return false;
        });
  }

  BottomNavigationBarItem _bottomGetItem(String tag) {
    BottomNavigationBarItem item;
    if (tag == '基础控件') {
      item =
          BottomNavigationBarItem(icon: Icon(Icons.bookmark), title: Text(tag));
    } else if (tag == '布局容器') {
      item = BottomNavigationBarItem(
          icon: Icon(Icons.settings_system_daydream), title: Text(tag));
    } else if (tag == '事件及动画') {
      item = BottomNavigationBarItem(
          icon: Icon(Icons.color_lens), title: Text(tag));
    } else if (tag == '文件及其他') {
      item = BottomNavigationBarItem(icon: Icon(Icons.insert_drive_file), title: Text(tag));
    }
    return item;
  }

  Widget _getWidget4() {
    return ListView.separated(itemBuilder: (context,index) {
        String title;
        String minTitle;
        var route;
        switch(index) {
          case 0:
            title = '文件操作';
            minTitle = '文件读写';
            route = FileRoute();
            break;
          case 1:
            title = 'HTTP操作';
            minTitle = '原始httpClinet';
            route = HttpClientRoute();
            break;
          case 2:
            title = 'Dio网络请求框架';
            minTitle = 'Dio';
            route = DiaRoute();
            break;
          case 3:
            title = 'Dio实例';
            minTitle = 'Dio_test';
            route = NewsTestRoute();
            break;
        }
      return _listTile(title: title,minTitle: minTitle,route: route);
    }, separatorBuilder: (context,index) {
      return Divider(height: 1,);
    }, itemCount: 4);
  }

  Widget _getWidget3({@required ThemeData theme}) {
    return ListView.separated(
        itemBuilder: (context, index) {
          String title;
          String minTitle;
          var route;
          switch(index) {
            case 0:
              title = 'InheritedWidget';
              minTitle = 'InheritedWidget';
              route = InheritedWidgetTest();
              break;
            case 1:
              title = 'ThemeTest';
              minTitle = 'ThemeTest';
              route = ThemeTest();
              break;
            case 2:
              title = 'FutureBuilderTest';
              minTitle = 'FutureBuilderTest';
              route = FutureBuilderTest();
              break;
            case 3:
              title = '主题更换';
              minTitle = '主题更换';
              route = ThemeModityTest();
              break;
            case 4:
              title = '通知测试';
              minTitle = '通知测试';
              route = NotificationRoute();
              break;
            case 5:
              title = '动画';
              minTitle = '动画';
              route = AnimationTestRoute();
              break;
            case 6:
              title = '触摸事件';
              minTitle = '触摸事件';
              route = TouchEventTest();
              break;
            case 7:
              title = '交织动画';
              minTitle = '交织动画';
              route = StaggerAnimation();
              break;
            case 8:
              title = '动画过渡';
              minTitle = '动画过渡';
              route = AnimatedDecoratedBoxRoute();
              break;
          }
          return _listTile(title: title,minTitle: minTitle,route: route);
        },
        separatorBuilder: (context, position) {
          return Divider(
            height: 1,
          );
        },
        itemCount: 9);
  }

  Widget _getWidget2() {
    return ListView.separated(
        itemBuilder: (context, index) {
          ListTile listTile;
          switch (index) {
            case 0:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('打开一个层叠布局'),
                subtitle: Text('层叠布局'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return StackTest();
                  }));
                },
              );
              break;
            case 1:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('AppThem'),
                subtitle: Text('appThem'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return NewScaffoldTest();
                  }));
                },
              );
              break;
            case 2:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('ListView'),
                subtitle: Text('scaffTest'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ScaffTest2();
                  }));
                },
              );
              break;
            case 3:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('贝塞尔曲线'),
                subtitle: Text('贝塞尔曲线'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return BezierPainter();
                  }));
                },
              );
              break;
            case 4:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('CustomScrollTest'),
                subtitle: Text('customScrollTest'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return CustomScrollTest();
                  }));
                },
              );
              break;
            case 5:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('滚动控制'),
                subtitle: Text('滚动控制'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ScrollControllerTest();
                  }));
                },
              );
              break;
            case 6:
              listTile = ListTile(
                trailing: Icon(
                  Icons.arrow_forward_ios,
                  size: 15,
                ),
                title: Text('CustomScrollViewTestRoute'),
                subtitle: Text('CustomScrollViewTestRoute'),
                dense: true,
                onTap: () {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return CustomScrollViewTestRoute();
                  }));
                },
              );
              break;
            case 7:
              listTile = _listTile(title:'打开一个弹性布局', minTitle: '弹性布局',route: FlexTest());
              break;
          }
          return listTile;
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 1,
          );
        },
        itemCount: 8);
  }

  Widget _getWidget1() {
    return ListView.separated(
        itemBuilder: (context, index) {
          String title;
          String minTitle;
          var route;
          switch (index) {
            case 0:
              title = "新的Fullter界面";
              minTitle = 'flutter路由';
              route = NewRoute();
              break;
            case 1:
              title = "打开传值页";
              minTitle = 'flutter传值';
              route = TipRoute(
                text: 'flutter传值',
              );
              break;
            case 2:
              title = "打开表单输入测试界面";
              minTitle = '表单输入控件';
              route = InputTest();
              break;
            case 3:
              title = "Dialog组件";
              minTitle = 'Dialog';
              route = DialogTest();
              break;
            case 4:
              title = "BOX组件";
              minTitle = 'BOX';
              route = BoxSizeBoxTest();
              break;
            case 5:
              title = '自定义组件';
              minTitle = '自定义组件';
              route = SelfWidgetTest();
              break;
          }
          return _listTile(title: title, minTitle: minTitle, route: route);
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 1,
          );
        },
        itemCount: 6);
  }

  ListTile _listTile({String title, String minTitle, route}) {
    return ListTile(
      title: Text(title),
      subtitle: Text(minTitle),
      dense: true,
      trailing: Icon(
        Icons.arrow_forward_ios,
        size: 15,
      ),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return route;
        }));
      },
    );
  }
}

class NewRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("这是新的界面"),
      ),
      body: Center(
        child: Text("这是一个Fullter界面"),
      ),
    );
  }
}
